package com.lsy.on_line.zaixian.controller;

import com.lsy.on_line.zaixian.model.entity.User;
import com.lsy.on_line.zaixian.model.request.LoginRequest;
import com.lsy.on_line.zaixian.service.IUserService;
import com.lsy.on_line.zaixian.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ShiYuan
 * @since 2022-07-24
 */
@RestController
@RequestMapping("/api/v1/pri/zaixian/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    /**
     * 注册接口
     * @param userInfo
     * @return
     */
    @PostMapping("/register")
    public JsonData register(@RequestBody Map<String,String> userInfo){
        int rows = iUserService.save(userInfo);
        return rows != -1 ? JsonData.buildSuccess()
                : JsonData.buildError("注册失败,请检查手机号码是否正确!或手机号码已存在！");
    }

    /**
     * 登录接口
     * @param loginRequest
     * @return
     */
    @PostMapping("/login")
    public JsonData login(@RequestBody LoginRequest loginRequest){

        String token = iUserService.findByPhoneAndPwd(loginRequest.getPhone(),loginRequest.getPwd());

        return token == null ? JsonData.buildError("登陆失败，账号或密码错误")
                : JsonData.buildSuccess(token);

    }

    /**
     * 根据用户id查询用户信息
     * @param request
     * @return
     */
    @GetMapping("/find_by_token")
    public JsonData findByToken(HttpServletRequest request){

       Integer userId = (Integer) request.getAttribute("user_id");

       if(userId == null){
           return JsonData.buildError("查询失败");
       }
       User user = iUserService.findByToken(userId);

       return JsonData.buildSuccess(user);
    }
}
